import {DefinePage, TableContainer} from "@/layout/Page";
import {Button, Flex, Form, Image, Input, Modal, Space, Switch, Table, Tag} from "antd";
import {PlusOutlined, SyncOutlined} from "@ant-design/icons";
import React, {useEffect, useRef, useState} from "react";
import {getModalSystemConfig, globalMessageApi, globalModalApi} from "@/components/OpComponent/Message";
import {
    addAvatarBorderUrl,
    getAvatarBorderListUrl,
    syncAvatarBorderUrl,
    updateAvatarBorderUrl
} from "@/api/system/avatar_border.ts";
import UploadPicture, {FileListType} from "@/components/Upload/UploadPicture";
import {getAvatarUploadUrl} from "@/utils/upload.ts";


const EditDialog = React.forwardRef((props: any, ref: any) => {
    const {
        getList
    } = props
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalEdit, setIsModalEdit] = useState(false)
    const [isRefresh, setIsRefresh] = useState(false)


    const [form] = Form.useForm()
    const [formValues, setFormValues] = useState<any>();

    const [url, setUrl] = useState("")
    const [fileList, setFileList] = useState<FileListType[]>([])


    useEffect(() => {
        console.log("fileList", fileList)
    }, [fileList])

    const handleOk = () => {
        // 进行校验
        if (!form) return
        form.validateFields().then((values) => {
            if (isModalEdit) {
                updateAvatarBorderUrl({
                    ...values,
                    status: values.status ? 0 : 1,
                    id: formValues.id
                }).then((res) => {
                    globalMessageApi.success(res.msg)
                    getList()
                    setIsModalOpen(false);
                })
            } else {
                addAvatarBorderUrl({
                    ...values,
                    status: values.status ? 0 : 1,
                }).then((res) => {
                    globalMessageApi.success(res.msg)
                    getList()
                    setIsModalOpen(false);
                })
            }
        })
    };


    const handleCancel = () => {
        form.resetFields();
        setIsModalOpen(false);
        if (isRefresh) getList()
    }

    const openModal = (data: any) => {
        setUrl("")
        setFileList([])
        setFormValues(data)
        console.log("data", data)
        if (data && data.id) {
            form.setFieldsValue({
                ...data,
                status: !data?.status
            })
            setUrl(getAvatarUploadUrl(data.id))
            const files = data.file ? [
                {
                    uid: data.file.id,
                    name: data.file.fileName,
                    status: 'success',
                    url: data.file.url
                }
            ] : []
            console.log("files", files)
            setFileList(files)
            setIsModalEdit(true)
            setIsModalOpen(true)
        } else {
            setIsModalEdit(false)
            setIsModalOpen(true)
        }
    }

    React.useImperativeHandle(ref, () => ({
        openModal: openModal
    }))
    return <Modal title={isModalEdit ? "编辑头像边框信息" : "新增头像边框信息"}
                  open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
                  modalRender={(dom) => (
                      <Form form={form} initialValues={formValues}>
                          {dom}
                      </Form>
                  )}
    >
        <Form.Item name={"title"} label="边框名称" rules={[{required: true, message: '边框名称不能为空!'}]}>
            <Input placeholder="请输入边框名称"/>
        </Form.Item>
        {isModalEdit &&
            <Form.Item name={"status"} label={"状态"} rules={[{required: true, message: '请选择对应的状态!'}]}>
                <Switch checkedChildren="启用" unCheckedChildren="禁用"/>
            </Form.Item>}
        {isModalEdit && <Form.Item name={"file"} label={"图片"}>
            <UploadPicture url={url} fileList={fileList} setStatus={setIsRefresh}/>
        </Form.Item>}
        <Form.Item name={"remark"} label={"备注"}>
            <Input.TextArea placeholder="请输入备注"/>
        </Form.Item>
    </Modal>
})


export default function () {

    const editDialogRef = useRef<any>(null)
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState([])
    const getTableDateList = () => {
        setLoading(true)
        getAvatarBorderListUrl().then((res) => {
            setData(res.data)
        }).finally(() => {
            setLoading(false)
        })
    }

    // 同步
    const syncHandle = async () => {
        const confirmed = await globalModalApi.confirm(getModalSystemConfig("是否开始同步?"));
        if (confirmed) {
            syncAvatarBorderUrl().then((res: any) => {
                globalMessageApi.success(res.msg)
                getTableDateList()
            })
        }
    }

    const columns: any = [
        {
            title: "编号",
            minWidth: 60,
            dataIndex: "id",
            align: "center"
        },
        {
            title: "名称",
            minWidth: 160,
            dataIndex: "title",
            ellipsis: true,
            align: "center"
        },
        {
            title: "状态",
            minWidth: 90,
            dataIndex: "status",
            align: "center",
            ellipsis: true,
            render: (text: any) => {
                return text === 1 ? <Tag color={"warning"}>停用</Tag> : <Tag color={"success"}>启用</Tag>
            }
        },
        {
            title: "同步",
            minWidth: 90,
            dataIndex: "url",
            align: "center",
            ellipsis: true,
            render: (record: any, text: any) => {
                const fileUrl = text.file?.url
                const url = text.url
                if (fileUrl != null && fileUrl === url) return <Tag color={"success"}>同步</Tag>
                return <Tag color={"warning"}>未同步</Tag>
            }
        },
        {
            title: "图片",
            minWidth: 90,
            dataIndex: "file",
            align: "center",
            ellipsis: true,
            render: (record: any) => {
                if (!record) return "-"
                return <Image src={record.url} alt="" style={{width: "60px", height: "60px"}}></Image>
            }
        },
        {
            title: "备注",
            minWidth: 90,
            dataIndex: "remark",
            align: "center",
            ellipsis: true,
        },
        {
            title: "操作",
            minWidth: 160,
            align: "center",
            fixed: "right",
            render: (record: any, index: number) => {
                return <Space key={index}>
                    <a onClick={() => editDialogRef.current.openModal(record)}>编辑</a>
                    <a className={"text-red-500"}>删除</a>
                </Space>
            }
        }

    ]

    useEffect(() => {
        getTableDateList()
    }, [])

    return <DefinePage>
        <Flex gap="small" vertical>
            <Flex align="center" gap="small">
                <Button icon={<PlusOutlined/>} type="primary"
                        onClick={() => editDialogRef.current.openModal()}>新增</Button>
                {/*同步地址 url */}
                <Button icon={<SyncOutlined/>} type={"primary"} danger onClick={syncHandle}>同步图片 url 数据</Button>
            </Flex>
            <Table
                rowKey="id"
                loading={loading}
                tableLayout="auto"
                dataSource={data}
                columns={columns}
                scroll={
                    {x: 'auto'}
                }
                pagination={false}
            >
            </Table>
        </Flex>
        <EditDialog ref={editDialogRef} getList={getTableDateList}/>
    </DefinePage>
}
